package com.example.demo.service.impl;

import com.example.demo.common.Result;
import com.example.demo.dto.DriverCUDTO;
import com.example.demo.dto.DriverGetDTO;
import com.example.demo.entity.Driver;
import com.example.demo.mapper.DriverMapper;
import com.example.demo.service.DriverService;
import com.example.demo.vo.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DriverServiceImpl implements DriverService {
    @Autowired
    private DriverMapper driverMapper;

    @Transactional
    @Override
    public Result batDelete(String[] ids) {
        for(String id : ids){
//            System.out.println("currentId:"+id);
            driverMapper.deleteDriver(Integer.parseInt(id));
        }
        return Result.success();
    }

    @Override
    public Result deleteDriver(Integer id) {
        int aff = driverMapper.deleteDriver(id);
        if (aff > 0) {
            return Result.success();
        }else{
            return Result.fail();
        }
    }

    @Override
    public Result addDriver(DriverCUDTO driverCreateDTO) {
        Driver driver = new Driver();
        driver.setName(driverCreateDTO.getName());
        driver.setSex(driverCreateDTO.getSex());
        driver.setBirthday(driverCreateDTO.getBirthday());
        driver.setLicense(driverCreateDTO.getLicense());
        driver.setPhone(driverCreateDTO.getPhone());
        int aff = driverMapper.insertDriver(driver);
        if (aff > 0) {
            return Result.success();
        }else{
            return Result.fail();
        }
    }

    @Override
    public Result updateDriver(DriverCUDTO driverUpdateDTO) {
        Driver driver = new Driver();
        driver.setId(driverUpdateDTO.getId());
        driver.setName(driverUpdateDTO.getName());
        driver.setSex(driverUpdateDTO.getSex());
        driver.setLicense(driverUpdateDTO.getLicense());
        driver.setPhone(driverUpdateDTO.getPhone());
        int aff = driverMapper.updateDriver(driver);
        if (aff > 0) {
            return Result.success();
        }else{
            return Result.fail();
        }
    }

    @Override
    public Result searchDriver(DriverGetDTO driverGetDTO) {
        Driver driver = new Driver();
        driver.setName(driverGetDTO.getName());
        driver.setSex(driverGetDTO.getSex());
        driver.setLicense(driverGetDTO.getLicense());
        driver.setPhone(driverGetDTO.getPhone());
        List<Driver> drivers = driverMapper.selectDriver(driver);
        ResponseData<Driver> responseData = new ResponseData<>();
        responseData.setList(drivers);
        responseData.setTotal(drivers.size());
        if (drivers.size() > 0) {
            return Result.success(responseData);
        }else {
            return Result.fail();
        }
    }
}
